import { createStore } from 'vuex'

const UI_PREFERENCE_STORAGE_KEY = 'shortlink_ui_preferences'

function loadUiPreferencesFromStorage() {
  try {
    const raw = localStorage.getItem(UI_PREFERENCE_STORAGE_KEY)
    if (!raw) return null
    return JSON.parse(raw)
  } catch (e) {
    return null
  }
}

function persistUiPreferencesToStorage(preferences) {
  try {
    localStorage.setItem(UI_PREFERENCE_STORAGE_KEY, JSON.stringify(preferences))
  } catch (e) {
    // ignore
  }
}

// 创建一个新的 store 实例
const store = createStore({
  state() {
    const defaults = {
      theme: 'light', // light | dark
      layout: 'top', // top | side
      primaryColor: '#2C85EC',
      compact: false
    }
    const saved = loadUiPreferencesFromStorage()
    const ui = { ...defaults, ...(saved || {}) }
    return {
      // domain: 'nurl.ink'
      domain: 's.nageoffer.com',
      ui
    }
  },
  getters: {
    uiTheme: (state) => state.ui.theme,
    uiLayout: (state) => state.ui.layout,
    uiPrimaryColor: (state) => state.ui.primaryColor,
    uiCompact: (state) => state.ui.compact
  },
  mutations: {
    setTheme(state, theme) {
      state.ui.theme = theme
      persistUiPreferencesToStorage(state.ui)
    },
    setLayout(state, layout) {
      state.ui.layout = layout
      persistUiPreferencesToStorage(state.ui)
    },
    setPrimaryColor(state, color) {
      state.ui.primaryColor = color
      persistUiPreferencesToStorage(state.ui)
    },
    setCompact(state, compact) {
      state.ui.compact = compact
      persistUiPreferencesToStorage(state.ui)
    }
  },
  actions: {
    initFromStorage({ commit }) {
      const saved = loadUiPreferencesFromStorage()
      if (saved) {
        if (saved.theme) commit('setTheme', saved.theme)
        if (saved.layout) commit('setLayout', saved.layout)
        if (saved.primaryColor) commit('setPrimaryColor', saved.primaryColor)
        if (typeof saved.compact === 'boolean') commit('setCompact', saved.compact)
      }
    }
  }
})

export default store
